/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.iqt;

import br.com.iqt.util.Indenter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

/**
 *
 * @author Arlino
 */
public class DriverWorkloadSqlserver implements DriverWorkload{
    private Dbms dbms;

    DriverWorkloadSqlserver(Dbms dbms) {
        this.dbms = dbms;
    }

    @Override
    public ArrayList getWorkLoad() throws ClassNotFoundException, SQLException {
        ArrayList workLoadList = new ArrayList();
        String driver = Dbms.driverSqlServer;
        String user = dbms.getUser();
        String password = dbms.getPassword();
        String url = "jdbc:sqlserver://" + dbms.getServer() + ";database=" + dbms.getDatabase();
        String sql = "select sql as current_query from master.dbo.syscacheobjects "
                        + "where objtype='Prepared' and cacheobjtype='Executable Plan' and sql like'()%' "
                        + "group by UPPER(sql)";

        Class.forName(driver);
        Connection connection = (Connection) DriverManager.getConnection(url, user, password);
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);
        while (resultSet.next()) {
            String query = resultSet.getString("current_query");
            query = Indenter.removeWhiteSpace(Indenter.unindent(query));
            workLoadList.add(query);
        }
        connection.close();
        return workLoadList;
    }
    
}
